<template>
  <div class="app-container unit-container">
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      v-show="showSearch"
      class="search-form"
    >
      <el-form-item label="单位名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入单位名称"
          clearable
          class="search-input"
          @keyup.enter="handleQuery"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="单位类型" prop="unitType">
        <el-select v-model="queryParams.unitType" placeholder="请选择单位类型" clearable class="search-select">
          <el-option
            v-for="dict in unitTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="search-select">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="search-buttons">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="toolbar-container">
      <div class="left-buttons">
        <el-button
          type="primary"
          class="add-button"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['product:unit:create']"
        >新增单位</el-button>
        <el-button
          type="danger"
          class="delete-button"
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['product:unit:delete']"
        >批量删除</el-button>
      </div>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </div>

    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="list"
        @selection-change="handleSelectionChange"
        class="main-table"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="单位名称" align="center" prop="name" min-width="120" />
        <el-table-column label="单位符号" align="center" prop="symbol" min-width="100" />
        <el-table-column label="单位类型" align="center" prop="unitType" min-width="120">
          <template #default="scope">
            <dict-tag :options="unitTypeOptions" :value="scope.row.unitType" />
          </template>
        </el-table-column>
        <el-table-column label="单位描述" align="center" prop="description" min-width="180" :show-overflow-tooltip="true" />
        <el-table-column label="排序" align="center" prop="sort" width="80" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 1 ? 'success' : 'danger'"
              class="status-tag"
            >
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['product:unit:update']"
            >修改</el-button>
            <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['product:unit:delete']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        class="pagination-container"
      />
    </div>

    <el-dialog 
      :title="title" 
      v-model="open" 
      width="500px" 
      append-to-body
      destroy-on-close
      class="unit-dialog"
    >
      <el-form ref="unitFormRef" :model="form" :rules="rules" label-width="100px" class="dialog-form">
        <el-form-item label="单位名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="单位符号" prop="symbol">
          <el-input v-model="form.symbol" placeholder="请输入单位符号" />
        </el-form-item>
        <el-form-item label="单位类型" prop="unitType">
          <el-select v-model="form.unitType" placeholder="请选择单位类型" class="form-select">
            <el-option
              v-for="dict in unitTypeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单位描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            placeholder="请输入单位描述"
            :rows="3"
            resize="none"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number 
            v-model="form.sort" 
            :min="0" 
            :max="999"
            controls-position="right"
            class="form-number" 
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.unit-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .search-form {
    padding: 24px;
    background: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 20px;

    .search-input {
      width: 240px;
    }

    .search-select {
      width: 200px;
    }

    .search-buttons {
      margin-left: 8px;
    }
  }

  .toolbar-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .left-buttons {
      display: flex;
      gap: 12px;

      .add-button {
        background: var(--el-color-primary);
        border-color: var(--el-color-primary);
        color: white;
        
        &:hover {
          background: var(--el-color-primary-light-3);
          border-color: var(--el-color-primary-light-3);
        }
      }

      .delete-button {
        &:disabled {
          cursor: not-allowed;
          opacity: 0.6;
        }
      }
    }
  }

  .table-container {
    background: white;
    border-radius: 4px;
    padding: 20px;
    
    .main-table {
      margin-bottom: 20px;
      
      :deep(.el-table__header) {
        background-color: #f5f7fa;
      }

      :deep(.el-table__row) {
        transition: all 0.3s ease;
        
        &:hover {
          background-color: #f5f7fa;
        }
      }
    }

    .status-tag {
      padding: 4px 12px;
      border-radius: 12px;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}

.unit-dialog {
  :deep(.el-dialog__body) {
    padding: 30px 20px;
  }

  .dialog-form {
    .form-select {
      width: 100%;
    }

    .form-number {
      width: 160px;
    }

    .el-textarea {
      font-family: inherit;
    }
  }

  .dialog-footer {
    text-align: right;
    padding-top: 20px;
  }
}

.el-table__row {
  transition: transform 0.3s ease;
  
  &:hover {
    transform: translateX(5px);
  }
}

.el-button {
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
}

@media screen and (max-width: 768px) {
  .unit-container {
    padding: 10px;
    
    .search-form {
      padding: 15px;
      
      .el-form-item {
        margin-bottom: 15px;
      }
    }
    
    .toolbar-container {
      flex-direction: column;
      gap: 10px;
      
      .left-buttons {
        width: 100%;
        justify-content: space-between;
      }
    }
  }
}
</style>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { ProductUnitVo, ProductUnitQuery, ProductUnitForm } from '@/api/product/unit/types';
import { getProductUnitList, getProductUnit, addProductUnit, updateProductUnit, deleteProductUnit, deleteProductUnitBatch } from '@/api/product/unit';
import { DICT_TYPE } from '@/utils/dict';
import type { DictDataOption } from '@/components/DictTag/types';
import { parseTime } from '@/utils/ruoyi';
import { ElMessage, ElMessageBox } from 'element-plus';

const { t } = useI18n(); // 国际化

const loading = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const list = ref<ProductUnitVo[]>([]);
const title = ref('');
const open = ref(false);

const queryFormRef = ref();
const unitFormRef = ref();

const queryParams = ref<ProductUnitQuery>({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
  unitType: undefined,
  status: undefined
});

const form = ref<ProductUnitForm>({
  name: '',
  symbol: '',
  unitType: undefined,
  description: '',
  sort: 0,
  status: 1
});

const rules = ref({
  name: [{ required: true, message: '单位名称不能为空', trigger: 'blur' }],
  symbol: [{ required: true, message: '单位符号不能为空', trigger: 'blur' }],
  unitType: [{ required: true, message: '单位类型不能为空', trigger: 'change' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
});

// 静态字典选项
const unitTypeOptions = ref([
  { label: '容量', value: 1, listClass: '', cssClass: '' },
  { label: '重量', value: 2, listClass: '', cssClass: '' },
  { label: '长度', value: 3, listClass: '', cssClass: '' },
  { label: '其他', value: 4, listClass: '', cssClass: '' }
] as DictDataOption[]);

const statusOptions = ref([
  { label: '禁用', value: 0, listClass: 'danger', cssClass: '' },
  { label: '正常', value: 1, listClass: 'success', cssClass: '' }
] as DictDataOption[]);

/** 查询商品单位列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await getProductUnitList(queryParams.value);
    list.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  reset();
};

/** 表单重置 */
const reset = () => {
  form.value = {
    name: '',
    symbol: '',
    unitType: undefined,
    description: '',
    sort: 0,
    status: 1
  };
  unitFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProductUnitVo[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加商品单位';
};

/** 修改按钮操作 */
const handleUpdate = async (row: ProductUnitVo) => {
  reset();
  const id = row.id || ids.value[0];
  const res = await getProductUnit(id);
  Object.assign(form.value, res.data);
  open.value = true;
  title.value = '修改商品单位';
};

/** 提交按钮 */
const submitForm = async () => {
  await unitFormRef.value?.validate();
  try {
    if (form.value.id) {
      await updateProductUnit(form.value);
      ElMessage.success('修改成功');
    } else {
      await addProductUnit(form.value);
      ElMessage.success('新增成功');
    }
    open.value = false;
    getList();
  } catch (error) {
    console.error(error);
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: ProductUnitVo) => {
  const unitIds = row?.id ? [row.id] : ids.value;
  await ElMessageBox.confirm('是否确认删除商品单位编号为"' + unitIds.join(',') + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });
  try {
    if (unitIds.length === 1) {
      await deleteProductUnit(unitIds[0]);
    } else {
      await deleteProductUnitBatch(unitIds);
    }
    await getList();
    ElMessage.success('删除成功');
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  getList();
});
</script> 